#region Using

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Collections.Specialized;
using System.Data;

using App_Code.Controls;
using BlogEngine.Core;

#endregion

public partial class widgets_Quotations_edit : WidgetEditBase
{
    protected struct ValidationExpression
    {
        /// <summary>
        /// Regular expression validation expression for date time.
        /// </summary>
        /// <remarks>http://www.regexlib.com/REDetails.aspx?regexp_id=610</remarks>
        public static readonly string DateTime = @"^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$";
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGrid();
        }

        grid.RowEditing += new GridViewEditEventHandler(grid_RowEditing);
        grid.RowUpdating += new GridViewUpdateEventHandler(grid_RowUpdating);
        grid.RowCancelingEdit += new GridViewCancelEditEventHandler(grid_RowCancelingEdit);
        grid.RowDeleting += new GridViewDeleteEventHandler(grid_RowDeleting);
        grid.PageIndexChanging +=new GridViewPageEventHandler(grid_PageIndexChanging);
        
        btnAdd.Click += new EventHandler(btnAdd_Click);
    }

    void btnAdd_Click(object sender, EventArgs e)
    {
        XmlDocument doc = Doc();
        XmlNode quotes = doc.SelectSingleNode("quotes");
        if (quotes == null)
        {
            quotes = doc.CreateElement("quotes");
            doc.AppendChild(quotes);
        }

        XmlNode quote = doc.CreateElement("quote");

        XmlAttribute id = doc.CreateAttribute("id");
        id.InnerText = Guid.NewGuid().ToString();
        quote.Attributes.Append(id);

        XmlAttribute quotation = doc.CreateAttribute("quotation");
        quotation.InnerText = txtQuotation.Text.Trim(); ;
        quote.Attributes.Append(quotation);

        XmlAttribute author = doc.CreateAttribute("author");
        author.InnerText = txtAuthor.Text.Trim();
        quote.Attributes.Append(author);

        XmlAttribute lastshown = doc.CreateAttribute("lastshown");
        lastshown.InnerText = txtLastShown.Text.Trim();
        quote.Attributes.Append(lastshown);

        quotes.AppendChild(quote);
        Save(doc);
        BindGrid();

        ClearAddForm();
    }

    private void ClearAddForm()
    {
        txtQuotation.Text = string.Empty;
        txtAuthor.Text = string.Empty;
        txtLastShown.Text = string.Empty;
    }

    private void BindGrid()
    {
        XmlDocument doc = Doc();
        XmlNodeList list = doc.SelectNodes("//quotes");
        if (list.Count > 0)
        {
            using (XmlTextReader reader = new XmlTextReader(doc.OuterXml, XmlNodeType.Document, null))
            {
                System.Data.DataSet ds = new System.Data.DataSet();
                ds.ReadXml(reader);
                if (ds.Tables.Count == 0)
                {
                    ds.Tables.Add(EmptyTable());
                }
                
                grid.DataSource = ds;
                grid.DataKeyNames = new string[] { "id" };
                grid.DataBind();
                ds.Dispose();
            }
        }
        ShowError(string.Empty);

    }

    DataTable EmptyTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("id");
        table.Columns.Add("quotation");
        table.Columns.Add("author");
        table.Columns.Add("lastshown");
        return table;

    }

    /// <summary>
    /// Handles the RowDeleting event of the grid control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewDeleteEventArgs"/> instance containing the event data.</param>
    void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        XmlDocument doc = Doc();
        string id = (string)grid.DataKeys[e.RowIndex].Value;
        XmlNode node = doc.SelectSingleNode("//quote[@id=\"" + id + "\"]");
        if (node != null)
        {
            node.ParentNode.RemoveChild(node);
            Save(doc);
            BindGrid();
        }
    }

    /// <summary>
    /// Handles the RowUpdating event of the grid control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
    void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        XmlDocument doc = Doc();
        string id = (string)grid.DataKeys[e.RowIndex].Value;
        TextBox textboxQuotation = (TextBox)grid.Rows[e.RowIndex].FindControl("txtQuotation");
        TextBox textboxAuthor = (TextBox)grid.Rows[e.RowIndex].FindControl("txtAuthor");
        TextBox textboxLastShown = (TextBox)grid.Rows[e.RowIndex].FindControl("txtLastShown");
        XmlNode node = doc.SelectSingleNode("//quote[@id=\"" + id + "\"]");

        if (node != null)
        {
            node.Attributes["quotation"].InnerText = textboxQuotation.Text;
            node.Attributes["author"].InnerText = textboxAuthor.Text;
            node.Attributes["lastshown"].InnerText = textboxLastShown.Text;
            grid.EditIndex = -1;
            Save(doc);
            BindGrid();
        }
    }

    /// <summary>
    /// Handles the RowEditing event of the grid control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
    void grid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grid.EditIndex = e.NewEditIndex;
        BindGrid();
    }

    /// <summary>
    /// Handles the RowCancelingEdit event of the grid control.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        grid.EditIndex = -1;
        //Bind data to the GridView control.
        BindGrid();
    }

    void grid_PageIndexChanging(Object sender, GridViewPageEventArgs e)
    {

        // Cancel the paging operation if the user attempts to navigate
        // to another page while the GridView control is in edit mode. 
        if (grid.EditIndex != -1)
        {
            // Use the Cancel property to cancel the paging operation.
            e.Cancel = true;

            // Display an error message.
            int newPageNumber = e.NewPageIndex + 1;
            ShowError("Please update the record before moving to page " + newPageNumber.ToString() + ".");
        }
        else
        {
            // Clear the error message.
            ShowError(string.Empty);

            // Move to the selected page:
            grid.PageIndex = e.NewPageIndex;
            BindGrid();

        }

    }



    void ShowError(string msg)
    {
        msg = msg.Trim();
        lblError.Text = msg;
        if (string.IsNullOrEmpty(msg))
            lblError.Visible = false;
        else
            lblError.Visible = true;
    }



    /// <summary>
    /// Saves this the basic widget settings such as the Title.
    /// </summary>
    public override void Save()
    {
        XmlDocument doc = Doc();
    }

    void Save(XmlDocument doc)
    {
        StringDictionary settings = GetSettings();
        settings["content"] = doc.InnerXml;
        SaveSettings(settings);
    }

    XmlDocument Doc()
    {
        StringDictionary settings = GetSettings();
        XmlDocument doc = new XmlDocument();
        if (settings["content"] != null)
            doc.InnerXml = settings["content"];

        return doc;
    }
}
